package com.gupao.rpc.protocol.spring.service;

import com.gupao.rpc.protocol.annotation.RpcRemoteService;
import com.gupao.rpc.protocol.server.NettyServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import java.lang.reflect.Method;
import java.net.UnknownHostException;

@Slf4j
public class SpringRpcProviderBean implements InitializingBean, BeanPostProcessor {

    private String host;
    private int port;

    public SpringRpcProviderBean(RpcServerProperties properties) throws UnknownHostException {
//        this.host = InetAddress.getLocalHost().getHostAddress();
        this.host = properties.getHost();
        this.port = properties.getPort();
    }

    /**
     * bean实例化的时候调用（调用构造方法之后被调用）
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("begin to deploy netty server to {} on port {}", host, port);
        new Thread(() -> {
            new NettyServer(host, port).start();
        }).start();
    }

    /**
     * bean实例化之后调用
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        // 包含自定义发布服务注解的类
        if (bean.getClass().isAnnotationPresent(RpcRemoteService.class)) {
            Method[] methods = bean.getClass().getDeclaredMethods();
            for (Method method : methods) {
                String key = bean.getClass().getInterfaces()[0].getName() + "." + method.getName();
                Meditor.beanMethodMap.put(key, new BeanMethod(bean, method));
            }
        }
        return bean;
    }
}
